import { resources, JsonAsset, BufferAsset } from "cc";
import { DEBUG } from "cc/env";
import { Tables, temp } from "../../template/schema";
import ByteBuf from "../../bright/serialization/ByteBuf";
import * as cfg from "../../template/schema";
/** 物品数据类 */
export class TempItem {
    /** 物品ID */
    id: number = 0;
    /** 道具类型 */
    type: number = 0;
    /** 稀有度 */
    quality: number = 0;
    /** 道具名称 */
    name: string = "";
    /** 道具描述 */
    desc: number = 0;
    /** 描述动态填充 */
    descUi: number = 0;
    /** 图片 */
    img: string = "";
    /** 是否可堆叠 */
    stackable: boolean = false;
    /** 可堆叠上限*/
    maxStack: number = 9999999999;
    /** 获取途径*/
    obtainMethod: number = 0;
    constructor(data?: any) {
        if (data) {
            this.id = data.id || 0;
            this.type = data.type || 0;
            this.quality = data.quality || 0;
            this.name = data.name || "";
            this.desc = data.desc || 0;
            this.descUi = data.descUi || 0;
            this.img = data.img || "";
            this.stackable = data.stackable || false;
            this.maxStack = data.maxStack || 9999999999;
            this.obtainMethod = data.obtainMethod || 0;
        }
    }
}


export class TemplateMgr {

    private static sInstance: TemplateMgr = null!;

    /** 物品数据 */
    public tempItem: { [key: number]: TempItem } = {};

    public static instance() {
        if (!TemplateMgr.sInstance) {
            TemplateMgr.sInstance = new TemplateMgr();
        }
        if (DEBUG) {
            // @ts-ignore
            window["TemplateMgr"] = TemplateMgr;
        }
        return TemplateMgr.sInstance;
    }

    /** 后面需要保证table初始化完成，加载配置成功后再进行游戏加载 */
    public templates: Tables = null!;

    /** 二进制配置 */
    private static dataMap = new Map<string, Uint8Array>();

    public init(cb: Function) {
        // this.loadJson(cb);
        this.loadBinary(cb);
    }

    /** 加载二进制 */
    public loadBinary(cb: Function) {
        const startTime = performance.now(); // 添加开始时间统计

        resources.loadDir<BufferAsset>("template1",
            function (err, assets) {
                if (err) {
                    console.error(err.message || err);
                    return;
                }

                assets.forEach(element => {
                    TemplateMgr.dataMap.set(element.name, new Uint8Array(element.buffer().slice(0, element.buffer().byteLength)));
                });

                console.log("静态配置加载完成");
                //@ts-ignore
                let tables = new cfg.Tables(TempMgr.getFileData);

                TempMgr.templates = tables;
                Templates = tables;

                const endTime = performance.now(); // 添加结束时间统计
                const loadTime = endTime - startTime; // 计算加载时间
                console.log(`二进制配置加载总耗时: ${loadTime.toFixed(2)}ms`); // 输出加载时间

                TempMgr.afterLoadJson(TempMgr);

                cb();
            })
    }

    private getFileData(fileName: string): ByteBuf | null {
        if (TemplateMgr.dataMap.has(fileName)) {
            return new ByteBuf(TemplateMgr.dataMap.get(fileName));
        }
        return null;
    }

    /** 加载Json */
    loadJson(cb: Function) {
        console.log("开始加载策划配置");
        const startTime = performance.now(); // 添加开始时间统计

        let selfThis = this;
        resources.loadDir<JsonAsset>("template1",
            function (err, assets) {
                if (err) {
                    console.error(err.message || err);
                    return;
                }

                let jsons: any = {};

                assets.forEach(element => {
                    jsons[element.name] = element.json;
                });

                let tables = new Tables((fileName) => {
                    return jsons[fileName];
                });

                console.log("配置加载完成");
                // console.log("测试输出 = " + tables.TbItem.get(10000)!.name);
                selfThis.templates = tables;
                Templates = tables;

                const endTime = performance.now(); // 添加结束时间统计
                const loadTime = endTime - startTime; // 计算加载时间
                console.log(`Json配置加载总耗时: ${loadTime.toFixed(2)}ms`); // 输出加载时间

                selfThis.afterLoadJson(selfThis);

                cb();
            })
    }

    afterLoadJson(selfThis: TemplateMgr) {
        //初始化物品数据
        selfThis.initTempItem(['Item_1', 'Item_2']);
    }

    /**
     * 分表数据
    */
    getSubTable(key: string): any {
        const tables = Templates[key as keyof typeof Templates];
        return tables;
    }

    getSubTableList(key: string): any[] {
        const table = this.getSubTable(key);
        if (!table) {
            return null!;
        }
        return table.getDataList();
    }

    getSubTableMap(key: string): Map<number, any> {
        const table = this.getSubTable(key);
        if (!table) {
            return null!;
        }
        return table.getDataMap();
    }




    /************************************* 物品 ************************************/

    /**
     * 初始化物品数据
     * @param tableNames 物品表名数组
     */
    private initTempItem(tableNames: string[]): void {
        this.tempItem = {};

        console.log("准备加载物品表：", tableNames);

        // 依次加载每个表的数据
        for (const tableName of tableNames) {
            console.log(`正在加载表 ${tableName}`);
            // 使用this.templates而不是Templates
            const table = (this.templates as any)[tableName];
            if (table && table.getDataList) {
                const itemList = table.getDataList();
                console.log(`表 ${tableName} 中的数据：`, itemList);
                console.log(`表 ${tableName} 中的数据数量：${itemList.length}`);
                for (const item of itemList) {
                    if (this.tempItem[item.id]) {
                        console.error(`物品ID重复: ${item.id}, 在表 ${tableName} 中发现重复`);
                    } else {
                        this.tempItem[item.id] = new TempItem(item);
                    }
                }
            } else {
                console.warn(`表 ${tableName} 不存在或没有getDataList方法`);
            }
        }

        // 输出初始化后的物品数据
        const itemCount = Object.keys(this.tempItem).length;
        console.log(`物品数据初始化完成，共加载 ${itemCount} 个物品：`);
        for (const id in this.tempItem) {
            const item = this.tempItem[id];
            const properties = Object.keys(item).filter(key => typeof (item as any)[key] !== 'function');
            const itemInfo = properties.map(key => `${key}: ${(item as any)[key]}`).join(', ');
            console.log(itemInfo);
        }

        console.log("测试输出 = " + TempMgr.getTempItem(101)?.name);
    }

    /**
     * 获取物品数据
     * @param id 物品ID
     * @returns 物品数据
     */
    public getTempItem(id: number): TempItem | null {
        return this.tempItem[id] || null;
    }
}

// 缩短代码
export let Templates: Tables = TemplateMgr.instance().templates;
export let TempMgr: TemplateMgr = TemplateMgr.instance();